package com.jxtc.enterprise.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.util.EnumMap;
import java.util.Map;

public class QrCodeUtil {

    /**
     * 生成正方形的二维码
     *
     * @param content 二维码中包含的信息（如：URL）
     * @param size    生成二维码图片的宽高（像素）
     */
    public static BufferedImage generate(String content, int size) {
        try {
            Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
            hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // L/M/Q/H
            hints.put(EncodeHintType.MARGIN, 1); // 边距(默认4)，可调小

            BitMatrix matrix = new com.google.zxing.qrcode.QRCodeWriter()
                    .encode(content, BarcodeFormat.QR_CODE, size, size, hints);

            // 你也可以自定义前景/背景色：new MatrixToImageConfig(fg, bg)
            return MatrixToImageWriter.toBufferedImage(matrix, new MatrixToImageConfig());
        } catch (WriterException e) {
            throw new RuntimeException("Failed to generate QR code", e);
        }
    }
}
